package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.CartBean;
import com.project.mapper.ICartMapper;
import com.project.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements ICartService {
    @Autowired
    private ICartMapper mapper;

    @Override
    public void add(CartBean cart) {
        QueryWrapper<CartBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId", cart.getProductId());
        qw.eq("fk_userId", cart.getUserId());
        CartBean cartBean = mapper.selectOne(qw);
        if (cartBean == null) {//表示购物无车记录无商品
            mapper.insert(cart);
        } else {
            cartBean.setNum(cartBean.getNum() + 1);
            mapper.updateById(cartBean);
        }
    }

    @Override
    public void del(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public void update(Integer id, Integer num) {
        if (num <= 0) {
            this.del(id);
            return;
        }
        CartBean cart = mapper.selectById(id);
        cart.setNum(num);
        mapper.updateById(cart);
    }

    @Override
    public List<CartBean> findByUser(Integer userId) {

        return mapper.findByUser(userId);
    }
}
